/**
 * 自动任务驱动器
 */

const state = {
  sequences: [], //任务队列
  currentItem: undefined,//当前执行项
  status: 0, //状态：0：停止，1：执行中，2：暂停中
  steps: 0, //总步骤数
  currentStep: 1, //当前执行第几步
  handles: {} //任务处理器
};

// actions
const actions = {
  //初始化任务
  initTask({commit, state}, {name, steps, sequences}) {
    console.info(`初始化自动化任务${name}。`)
    state.sequences = sequences;
    state.steps = steps;
    state.currentStep = 0;
    state.handles = {};
  },

  //开始任务
  start({commit, state, dispatch}) {
    state.status = 1;
    if (!state.sequences.length) return alert('任务执行完毕！');
    const item = state.sequences.shift();
    state.currentItem = item;
    dispatch('forward'); //执行下一步
  },

  //前进到下一步
  forward({commit, state, dispatch}) {
    if (state.status == 0) return; //暂停不执行后续步骤
    let nextStep = state.currentStep + 1;
    if (nextStep > state.steps) {
      state.currentStep = 0;
      dispatch('start'); //开始下一组任务
    } else {
      state.currentStep = nextStep;
      const handle = state.handles[nextStep];
      handle(state.currentItem); //执行处理器 参数携带当前执行项
    }
  },

  //暂停任务
  pause({commit, state}) {
    state.status = 0;
  },

  //继续任务
  continue({commit, state, dispatch}) {
    state.status = 1;
    dispatch('forward'); //执行下一步
  },
};

const mutations = {
  SET_STEP_HANDLE(state, node) {
    state.handles[node.step] = node.handle;
  },
};

export default {
  namespaced: true,
  state,
  actions,
  mutations
};
